﻿Imports System
Imports System.CodeDom
Imports System.Globalization
Imports System.Text
Imports System.Workflow.ComponentModel.Compiler

Namespace System.Workflow.Activities.Rules
    Friend Class ThisExpression
        Inherits RuleExpressionInternal
        ' Methods
        Friend Overrides Sub AnalyzeUsage(ByVal expression As CodeExpression, ByVal analysis As RuleAnalysis, ByVal isRead As Boolean, ByVal isWritten As Boolean, ByVal qualifier As RulePathQualifier)
            If ((Not analysis.ForWrites OrElse isWritten) AndAlso (analysis.ForWrites OrElse isRead)) Then
                Dim builder As New StringBuilder("this/")
                Dim qualifier2 As RulePathQualifier = qualifier
                Do While (Not qualifier2 Is Nothing)
                    builder.Append(qualifier2.Name)
                    If (qualifier2.Name = "*") Then
                        If (Not qualifier2.Next Is Nothing) Then
                            Throw New NotSupportedException(Messages.InvalidWildCardInPathQualifier)
                        End If
                    Else
                        builder.Append("/")
                    End If
                    qualifier2 = qualifier2.Next
                Loop
                analysis.AddSymbol(builder.ToString)
            End If
        End Sub

        Friend Overrides Function Clone(ByVal expression As CodeExpression) As CodeExpression
            Return New CodeThisReferenceExpression
        End Function

        Friend Overrides Sub Decompile(ByVal expression As CodeExpression, ByVal stringBuilder As StringBuilder, ByVal parentExpression As CodeExpression)
            stringBuilder.Append("this")
        End Sub

        Friend Overrides Function Evaluate(ByVal expression As CodeExpression, ByVal execution As RuleExecution) As RuleExpressionResult
            Return execution.ThisLiteralResult
        End Function

        Friend Overrides Function Match(ByVal expression As CodeExpression, ByVal comperand As CodeExpression) As Boolean
            Return True
        End Function

        Friend Overrides Function Validate(ByVal expression As CodeExpression, ByVal validation As RuleValidation, ByVal isWritten As Boolean) As RuleExpressionInfo
            If isWritten Then
                Dim item As New ValidationError(String.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, New Object() { GetType(CodeThisReferenceExpression).ToString }), &H17A)
                item.UserData.Item("ErrorObject") = expression
                validation.Errors.Add(item)
                Return Nothing
            End If
            Return New RuleExpressionInfo(validation.ThisType)
        End Function

    End Class
End Namespace

